package com.zws.cucumber.glue;

import com.zws.cucumber.util.colorfullog.ZwsColorfulLogger;
import com.zws.cucumber.util.colorfullog.ZwsPrintTableHelper;
import io.cucumber.datatable.DataTable;
import io.cucumber.java.en.Given;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.zws.cucumber.expander.ZwsStr.expand;

public class ZwsSystemPropertiesGlue {

    private static final Logger logger = ZwsColorfulLogger.of(ZwsSystemPropertiesGlue.class);

    @Given("prepare system properties")
    public void prepareSystemProperties(DataTable table) {
        Map<String, String> map = table.asMap(String.class, String.class);
        map.forEach((k, v) -> {
            String expandedValue = expand(v);
            logger.debug("prepare system properties, key: {}, value: {}", k, expandedValue);
            System.setProperty(k, expandedValue);
        });
    }

    @Given("print system properties")
    public void printSystemProperties() {
        List<String> keyList = Arrays.asList("Key", "Type", "Value");
        List<Map<String, Object>> rowList = System.getProperties().entrySet()
                .stream()
                .map(e -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("Key", e.getKey().toString());
                    map.put("Type", e.getValue() != null ? e.getValue().getClass().getSimpleName() : "[null]");
                    map.put("Value", e.getValue());
                    return map;
                })
                .collect(Collectors.toList());

        ZwsPrintTableHelper.printTable0("System Properties", Pair.of(keyList, rowList));
    }

    @Given("print system property {string}")
    public void printSystemProperty(String key) {
        if (System.getProperties().containsKey(key)) {
            logger.debug("print system property, key: {}, value: {}", key, System.getProperty(key));
        } else {
            logger.debug("<y>print system property, no such key: {}</y>", key);
        }
    }
}
